package com.example.commonlib.httplib.interceptor;

import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.example.commonlib.BuildConfig;
import com.example.commonlib.commonutil.MLog;
import com.example.commonlib.commonutil.SPUtils;
import com.example.commonlib.httplib.utils.ASCIISortUtil;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Create by xjs
 * _______date : 17/8/4
 * _______description:对请求参数添加请求头，刷新token,跳转登录
 */
public class UrlInterceptor implements Interceptor {
    public String hostInit = "";
    public Context context;

    public UrlInterceptor() {
        super();
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl httpUrl = request.url();
        String strAsc;
        //第一步 ASCII排序
        if ("POST".equals(request.method())) {
            RequestBody requestBody = request.body();
            if (requestBody != null && requestBody.contentType() != null && requestBody.contentType().type() != null && requestBody.contentType().type().contains("multipart")) {
                strAsc = getASCIISortString(httpUrl);
            } else {
                strAsc = postASCIISortString(request);
            }

        } else if ("PUT".equals(request.method())) {
            strAsc = postASCIISortString(request);
        } else if ("DELETE".equals(request.method())) {
            strAsc = getASCIISortString(httpUrl);
        } else {
            strAsc = getASCIISortString(httpUrl);
        }

        Log.e("url------->",  request.url().toString());
        Log.e("params------->",  strAsc);
        String tokenStr = SPUtils.getToken();
        Response response = chain.proceed(requestBuild(request, strAsc,tokenStr).build());
//        if (response.code() == 401) {   //token过期
//            if (TextUtils.isEmpty(hostInit)) {
//                return response;
//            }
//            Request tokenRequest = new Request.Builder()
//                    .url(hostInit + "/api/get_token")
//                    .get()
//                    .build();
//            Request.Builder builder = tokenRequest.newBuilder();
//            Response tokenResponse = chain.proceed(builder.build());
//            if (tokenResponse.code() == 200) {
//                //获取token成功
//                TokenBean tokenBean = new GsonBuilder().create().fromJson(tokenResponse.body().string(), TokenBean
//                        .class);  //更新后的token
//                //更新token
//                TokenHelper tokenHelper = TokenHelper.getInstance(context);
//                tokenHelper.putTokenBean(tokenBean);
//                //把新的token保存在本地
//                SPUtils.setParam(SPUtils.TOKEN, context, SPUtils.TOKEN, tokenBean.getData());
//                Response newResponse = chain.proceed(requestBuild(request, strAsc).build());
//                return newResponse;
//            } else if (tokenResponse.code() == 401) {
//                return tokenResponse;   //token 失效
//            } else if (response.code() == 400) {
//                //没有登录或者登录失效
//                return tokenResponse;
//            }
//        }
        return response;
    }

    private static Request.Builder requestBuild(Request request, String asc, String tokenStr) {
        Request.Builder builder = request.newBuilder();
        MLog.e("token",tokenStr);
        builder.addHeader("Authorization", TextUtils.isEmpty(tokenStr) ? "" :tokenStr);
        builder.addHeader("version", BuildConfig.VERSION_NAME);
        if (Build.VERSION.SDK != null) {
            builder.addHeader("Connection", "close");
        }
        return builder;
    }

    private static String getASCIISortString(HttpUrl httpUrl) {
        int size = httpUrl.querySize();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < size; i++) {
            map.put(httpUrl.queryParameterName(i), httpUrl.queryParameterValue(i));
        }
        return ASCIISortUtil.formatQueryParaMap(map, false);
    }

    private static String postASCIISortString(Request request) {
        Map<String, String> map = new HashMap<>();
        if (request.body() instanceof FormBody) {
            FormBody formBody = (FormBody) request.body();
            for (int i = 0; i < formBody.size(); i++) {
                map.put(formBody.name(i), formBody.value(i));
            }
        } else {
            //buffer流
            Buffer buffer = new Buffer();
            try {
                request.body().writeTo(buffer);
                Log.e("-------->", request.body() + "---");
                String oldParams = buffer.readUtf8();
                map = new GsonBuilder().create().fromJson(oldParams, HashMap.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (map == null || map.isEmpty()) return "";
        return ASCIISortUtil.formatQueryParaMap(map, false);
    }
}
